//
//  ControlCenterView.swift
//  ReadHub
//
//  Created by testypp on 2017/12/20.
//  Copyright © 2017年 longyiqun. All rights reserved.
//

import Foundation
import UIKit

protocol ControlCenterViewDelegate: class {
    func stateChanged(scrollDirection: UICollectionViewScrollDirection)
    func stateChanged(scrollToEdgeEnabled: Bool)
}

class ControlCenterView: UIView {
	
    let segmentedControl = UISegmentedControl()
    let scrollToLabel = UILabel()
	
	weak var delegate: ControlCenterViewDelegate?
	
	override init(frame: CGRect) {
		super.init(frame: frame)
		
		backgroundColor = UIColor.clear
		
		// layout subviews
		preservesSuperviewLayoutMargins = false
		
		let scrollToStackView = UIStackView()
		scrollToStackView.alignment = .fill
		scrollToStackView.addArrangedSubview(scrollToLabel)
		//scrollToStackView.addArrangedSubview(scrollToSwitch)
		
		addSubview(segmentedControl)
		addSubview(scrollToStackView)
		segmentedControl.translatesAutoresizingMaskIntoConstraints = false
		scrollToStackView.translatesAutoresizingMaskIntoConstraints = false
        
		
        NSLayoutConstraint.activate([
            segmentedControl.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor, constant: 15),
            segmentedControl.centerXAnchor.constraint(equalTo: layoutMarginsGuide.centerXAnchor),
            
            scrollToStackView.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor, constant: 15),
            scrollToStackView.topAnchor.constraint(equalTo: segmentedControl.bottomAnchor, constant: 15),
            scrollToStackView.trailingAnchor.constraint(equalTo: layoutMarginsGuide.trailingAnchor, constant: -15),
            scrollToStackView.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor, constant: -15)
            ])
	}
	
	required init?(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
    // MARK: - Actions

    @objc func controlStateDidChange(sender: UISegmentedControl) {
        guard let scrollDirection = UICollectionViewScrollDirection(rawValue: sender.selectedSegmentIndex) else { return }
        delegate?.stateChanged(scrollDirection: scrollDirection)
    }

    @objc func switchStateDidChange(sender: UISwitch) {
        delegate?.stateChanged(scrollToEdgeEnabled: sender.isOn)
    }
	
}
